﻿package com.gobang.netmode.search;

/**************************
 * 遍历局域网的IP
 * 一个类一个线程,对应一个IP,进行连接试着连接
 * 如果连接成功则把socket类传给clientSearchThread,另开辟一个线程,与服务器进行信息交换
 * 并把该类clientSearchThread的实例存在SearchJFrame.server.add()中
 * 
 * 
 **************************/

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import com.gobang.gobangui.MainWindowUI;
import com.gobang.netmode.sendandreceive.Message;
import com.gobang.netmode.sendandreceive.MessageMSG;
import com.gobang.netmode.sendandreceive.Order;
import com.gobang.netmode.sendandreceive.SendAndReceive;
import com.gobang.netmode.util.ClientDataClass;

public class ErgodicIpOfLANThread extends Thread {
	String IP;
	Socket socket;
	SendAndReceive sendAndReceive;
	int count;
	public ErgodicIpOfLANThread(String IP, int count) {
		// TODO Auto-generated constructor stub
		this.IP = IP;
		this.count = count;
	}

	public void run() {
		// TODO Auto-generated method stub
		try {
			socket = new Socket();
			SocketAddress socketAddress = new InetSocketAddress(IP, SearchJFrameOfLAN.portOfLAN);
			socket.connect(socketAddress, 5000);
			sendAndReceive = new SendAndReceive(socket);
			Message message = new Message();
			ClientDataClass c = new ClientDataClass("游客", null, 0, MainWindowUI.getID());
			message.msg = MessageMSG.ORDER;
			message.clientDataClass = c;
			message.order = Order.SEARCH;
			if(sendAndReceive.sendMessage(message)){
				System.out.println("ErgodicIpOfLANThread.run()发送信息成功");
				try {
					message = sendAndReceive.receiveMessage();
					System.out.println("ErgodicIpOfLANThread.run()收到信息"+message);
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					message = null;
				}
				if(message != null && message.serverMessage != null){
					SearchJFrameOfLAN.serverMessageVector.add(message.serverMessage);
					new Thread() {
						public void run() {
							SearchJFrameOfLAN.showServer();
						}
					}.start();//单线程用于及时显示信息
				}
			}
			sendAndReceive.close();
			SearchJFrameOfLAN.addProgressBarValue(count);
		} catch (UnknownHostException e) {
			SearchJFrameOfLAN.addProgressBarValue(count);
			// TODO Auto-generated catch block
		} catch (IOException e) {
			SearchJFrameOfLAN.addProgressBarValue(count);
			// TODO Auto-generated catch block
			
		}
	}
}
